﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace AccumulateApp.Helper
{
    /// <summary>
    /// 反射帮助类
    /// </summary>
    public static class ReflectHelper
    {
        /// <summary>
        /// 返回指定类型的指定列名的属性数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cols"></param>
        /// <returns></returns>
        public static PropertyInfo[] GetTypeProperties<T>(string cols)
        {
            Type type = typeof(T);
            //将列名字符串转换成List,转换成小写
            List<string> listCols = cols.GetStrList(',', true);
            //获取所有属性
            PropertyInfo[] properties = type.GetProperties();
            if (listCols != null && listCols.Count > 0)
            {
                properties = properties.Where(p => listCols.Contains(p.Name.ToLower())).ToArray();
            }
            return properties;
        }

        /// <summary>
        /// 获取对象的属性值
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="propertyName">属性名</param>
        /// <returns>属性值</returns>
        public static object GetPropertyValue(object obj, string propertyName)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }
            if (string.IsNullOrWhiteSpace(propertyName))
            {
                throw new ArgumentNullException(nameof(propertyName));
            }
            var property = obj.GetType().GetProperty(propertyName);
            if (property == null)
            {
                throw new ArgumentException($"对象 {obj.GetType().FullName} 中不存在属性 {propertyName}");
            }
            return property.GetValue(obj);
        }

        /// <summary>
        /// 设置对象的属性值
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="propertyName">属性名</param>
        /// <param name="value">属性值</param>
        public static void SetPropertyValue(object obj, string propertyName, object value)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }
            if (string.IsNullOrWhiteSpace(propertyName))
            {
                throw new ArgumentNullException(nameof(propertyName));
            }
            var property = obj.GetType().GetProperty(propertyName);
            if (property == null)
            {
                throw new ArgumentException($"对象 {obj.GetType().FullName} 中不存在属性 {propertyName}");
            }
            property.SetValue(obj, value);
        }
    


    }
}
